axios.interceptors.request.use(
	config => {
		config.headers['authorization'] = localStorage.authorization;
		return config;
	}, function (error) {
		return Promise.reject(error);
	}
);


// 响应拦截
axios.interceptors.response.use(function (response) {
	return response;
},function (error) {
	if (error.response.status === 401) {
		window.parent.location = defaultRedirectUrl
	}
	return Promise.reject(error);
});



//格式化时间
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

/**
 * 根据id初始化日期
 * @param id
 */
function initDatetimepicker(id) {
	$('#'+id).datetimepicker({
		format : 'yyyy-mm-dd hh:ii:00',
		language : 'zh-CN',
		minuteStep : 1
	}); 
}

function openWindow(url, width, height) {
    var w_percent = width ? width : 7;
    var h_percent = height ? height : 7;
    var widths = (window.screen.availWidth) * w_percent / 10;
    var heights = (window.screen.availHeight) * h_percent / 10;
    var iLeft = (window.screen.availWidth - widths) / 2;
    var iTop = (window.screen.availHeight - heights) / 2;

    return window.open(url, '_blank','scrollbars=yes,width=' + widths + ',height=' + heights + ',left=' + iLeft + ',top=' + iTop + '');
}

//字符串转数组
function stringToArray(str) {
	if(str == null || str == '') {
		return [];
	}

	return str.split(";");
}

//多选框-全选
function chkAll_onclick(obj,chk){
	var chks = document.getElementsByName(chk);
	for( var i = 0 ; i < chks.length ; i++ ){
		chks[i].checked = obj.checked;
	}
}
//多选框-单选
function chk_onclick(obj,chk,chkAll){
	var chks = document.getElementsByName(chk);
	var	chkAll=document.getElementsByName(chkAll);
	if(obj.checked==false)
			chkAll[0].checked=false;
	else{
		var j=1;
		for( var i = 0 ; i < chks.length ; i++ ){
			if(chks[i].checked==false){
				j=2;
				break;
			}
		}
		if (j==1)
			chkAll[0].checked=true;
	}
}


//根据真实长度截取（英文1个长度，中文占用2个长度）
function substring_real(data,sub_len){
	var len = 0;
	for (var i=0; i<data.length; i++) {
		if (data.charCodeAt(i)>127 || data.charCodeAt(i)==94) {
			len += 2;
		} else {
			len ++;
		}
		if(len > sub_len){
			return data.substring(0,i)+"···";
		}
	}
	return data;
}

//** ================================ dataTable 的一些操作 ↓ =======================================
//获得表格
function getTable(id) {
	return $("#"+id).DataTable();
}

//获得表格行数据
function getRowDataTable(id, tr) {
	return getTable(id).row(tr).data();
}

//获得表格所有数据
function getAllDataTable(id) {
	return getTable(id).data();
}

//重新加载表格
function reloadTable(id) {
	getTable(id).ajax.reload();
}

//清空表格
function clearTable(id) {
	getTable(id).clear().draw();
}

//更新表格一行(前端更新)
function updateTable(id, tr) {
	getTable(id).row(tr).invalidate();
}

/**
 * 将数据灌入表格，仅支持td对应数据中的字段的情况
 * 请注意加上符合要求的class
 */
function loadTable(id, data) {
	var tds = $("#"+id).find('td[class="loadTable"]');
	for(var i = 0; i < tds.length; i++) {
		var td = $(tds[i]);
		var nameAttr = data[td.attr('id')];
		td.html(nameAttr);
	}
}

let Language = {
	"lengthMenu": "每页  _MENU_ 行",
	"zeroRecords": "没有找到记录",
	"info": "当前 _START_ 到  _END_， 总共  _TOTAL_ 记录",
	"infoEmpty": "无记录",
	"paginate" : {
		"first" : "首页",
		"last" : "末页",
		"next" : "下一页",
		"previous" : "上一页"
	}
}




function getQueryString(name) {
	var strHref = window.location.href;
	var intPos = strHref.indexOf("?");
	var strRight = strHref.substr(intPos + 1);
	var arrTmp = strRight.split("&");
	for(var i = 0; i < arrTmp.length; i++) {
		var arrTemp = arrTmp[i].split("=");
		if(arrTemp[0].toUpperCase() == name.toUpperCase()) return arrTemp[1];
	}
	return "";
}

/*删除地址栏中，指定的参数名*/
function delParam(paramKey) {
	var url = window.location.href;
	var urlParam = window.location.search.substr(1);
	var beforeUrl = url.substr(0, url.indexOf("?"));
	var nextUrl = "";
	var arr = new Array();
	if (urlParam != "") {
		var urlParamArr = urlParam.split("&"); //将参数按照&符分成数组
		for (var i = 0; i < urlParamArr.length; i++) {
			var paramArr = urlParamArr[i].split("="); //将参数键，值拆开
			//如果键与要删除的不一致，则加入到参数中
			if (paramArr[0] != paramKey) {
				arr.push(urlParamArr[i]);
			}
		}
	}
	if (arr.length > 0) {
		nextUrl = "?" + arr.join("&");
	}
	url = beforeUrl + nextUrl;
	return url;
}

function dataFilterFunc(json) {
	let result = {};
	let jsonData = $.parseJSON(json)
	if (jsonData.success) {
		let resultData = jsonData.data;
		result.recordsTotal = resultData.totalItemNum;
		result.recordsFiltered = resultData.totalItemNum;
		result.data = resultData.data;
	} else {
		result.recordsTotal = 0;
		result.recordsFiltered = 0;
		result.data = [];
	}
	return JSON.stringify(result);
}

function dataListFilterFunc(json) {
	let d = $.parseJSON(json)
	let b = $.parseJSON("{\"data\":[]}")
	if (d.success) {
		if (d.dataList == null) {
			return JSON.stringify(b);
		}
		b.data = d.dataList;
		return JSON.stringify(b);
	} else {
		return JSON.stringify(b);
	}
}

function getHeaders() {
	return { authorization: localStorage.authorization }
}

function errorFunc(XMLHttpRequest, textStatus, errorThrown) {
}



















function create() {
	let json = $("#createForm").serializeObject()
	axios({
		method: 'post',
		url: createUrl,
		data: json
	}).then(response => {
		let data = response.data;
		if (data.success) {
			resetForm("createForm")
			$("#createModal").modal('hide')

			search()
		} else {
			alert(data.message);
		}
	})
}

function remove(id) {
	axios({
		method: 'post',
		url: deleteUrl,
		data: {
			id: id
		}
	}).then(response => {
		let data = response.data;
		if (data.success) {
			search()
		} else {
			alert(data.message);
		}
	})
}

function update() {
	axios({
		method: 'post',
		url: updateUrl,
		data: $("#updateForm").serializeObject()
	}).then(response => {
		let data = response.data;
		if (data.success) {
			resetForm("updateForm")
			$("#updateModal").modal('hide')

			search()
		} else {
			alert(data.message);
		}
	})
}
